import { Cascader } from 'antd';
import { useEffect, useState } from 'react';
import styles from './index.less';

export type areaItemType = {
  code: string;
  name: string;
  children?: areaItemType[];
};

type CascaderType = 'province' | 'city' | 'area';
type PropsType = {
  type?: CascaderType;
  value: string[] | string;
  placeholder?: string;
  onChange: (e?: string[], option?: areaItemType[]) => void;
};

const AreaSelect: React.FC<PropsType> = ({
  value,
  type = 'area',
  placeholder = '请选择省、市、区',
  onChange,
}: PropsType) => {
  const [options, setOptions] = useState<areaItemType[]>();

  useEffect(() => {
    const getData = async () => {
      let data;
      data = (await import('./pca-code.json')).default;
      switch (type) {
        // 省
        case 'province': {
          const list = JSON.parse(JSON.stringify(data)).map((item: areaItemType) => {
            delete item.children;
            return item;
          });
          setOptions(list);
          break;
        }
        // 省市
        case 'city': {
          const list = JSON.parse(JSON.stringify(data)).map((item: areaItemType) => {
            item.children?.forEach((item2: areaItemType) => {
              if (item2.children) {
                delete item2.children;
              }
            });
            return item;
          });
          setOptions(list);
          break;
        }
        default: {
          setOptions(data);
        }
      }
    };
    if (type) {
      getData();
    }
  }, [type]);

  {
    // 省市区街道的下拉框
    const val = value as string[];
    return (
      <Cascader
        value={val?.some((v) => v) ? val : ['']}
        fieldNames={{ label: 'name', value: 'name', children: 'children' }}
        expandTrigger="hover"
        options={options}
        placeholder={placeholder}
        onChange={(e, option) => {
          onChange(e as string[], option as unknown as areaItemType[]);
        }}
        className={styles.cascader}
      />
    );
  }
};

export default AreaSelect;
